from django.shortcuts import render, HttpResponse, redirect, reverse
from crm import models
import hashlib
from crm.forms import RegForm


def login(request):
    if request.method == 'POST':

        user = request.POST.get('username')
        pwd = request.POST.get('password')
        md5 = hashlib.md5()
        md5.update(pwd.encode('utf-8'))
        pwd = md5.hexdigest()

        obj = models.UserProfile.objects.filter(username=user, password=pwd, is_active=True).first()
        if obj:
            # session保存用户的id 登陆状态
            request.session['user_id'] = obj.pk
            request.session['is_login'] = '1'

            return redirect('crm:customer_list')
        return render(request, 'login.html', {'error': '用户名或密码错误'})

    return render(request, 'login.html')


def reg(request):
    form_obj = RegForm()
    if request.method == 'POST':
        form_obj = RegForm(request.POST)
        if form_obj.is_valid():
            form_obj.save()  # 新增
            return redirect('crm:login')
    return render(request, 'reg.html', {'form_obj': form_obj})
